/*
 *
 * Copyright Eclub organization.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 * http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.eclub.emotion.rootstone.serializer.scanning;

import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

import org.apache.log4j.Logger;

import com.eclub.emotion.rootstone.server.ResourceFinder;

/**
 * A utility class that scans entries in jar files.
 * 
 * @author jun.yang, Wincor Nixdorf International GmbH
 */
public class JarFileScanner implements ResourceFinder {

	private Logger log = Logger.getLogger(JarFileScanner.class);

	private final JarInputStream jarInputStream;

	private final String parent;

	public JarFileScanner(InputStream inputStream, String parent) throws IOException {
		this.jarInputStream = new JarInputStream(inputStream);
		this.parent = parent;
	}

	private JarEntry next = null;

	@Override
	public boolean hasNext() {
		if (next == null) {
			try {
				do {
					this.next = jarInputStream.getNextJarEntry();
				} while (next != null && (next.isDirectory() || !next.getName().startsWith(parent)));
			} catch (IOException e) {
				log.error("Unable to read the next jar entry.", e);
				return false;
			} catch (SecurityException e) {
				log.error("Unable to read the next jar entry.", e);
				return false;
			}
		}

		if (next == null) {
			try {
				jarInputStream.close();
			} catch (IOException e) {
				log.error("Unable to close jar file.", e);
			}

			return false;
		}

		return true;
	}

	@Override
	public String next() {
		if (next != null || hasNext()) {
			final String name = next.getName();
			next = null;
			return name;
		}

		throw new NoSuchElementException();
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	@Override
	public InputStream open() {
		return jarInputStream;
	}

	@Override
	public void reset() {
		throw new UnsupportedOperationException();
	}

}
